package com.erp.service.impl;

import com.erp.entity.Perms;
import com.erp.entity.Role;
import com.erp.entity.RolePerms;
import com.erp.mapper.RoleMapper;
import com.erp.mapper.RolePermsMapper;
import com.erp.service.PermsService;
import com.erp.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author pyj
 * @since 2020-11-07
 */
@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private RolePermsMapper rolePermsMapper;

    @Autowired
    private PermsService permsService;
    
    @Override
    public Role findRoleByName(String name) {
        return roleMapper.findRoleByName(name);
    }

    @Override
    public List<Role> getAllRoles() {
        return roleMapper.getAllRoles();
    }

    @Override
    public List<Role> getAll() {
        return roleMapper.getAll();
    }

    @Override
    public int add(Role role) {
        // 添加新的角色
        // 修改角色权限中间表
        roleMapper.add(role);
        RolePerms temp = new RolePerms();
        for (Perms p : role.getPerms()) {
            Perms perm = permsService.findPermsByName(p.getName());
            temp.setRid(role.getId());
            temp.setPid(perm.getId());
            rolePermsMapper.add(temp);
        }
        return role.getId();
    }

    @Override
    public int delete(Integer id) {
        rolePermsMapper.deleteByRid(id);
        return roleMapper.delete(id);
    }

    @Override
    public int update(Role role) {
        // 更新role角色名字
        roleMapper.update(role);
        // 更新中间角色中间表
        // 先删除旧权限，再新增新权限
        rolePermsMapper.deleteByRid(role.getId());
        for (Perms p : role.getPerms()) {
            Perms perm = permsService.findPermsByName(p.getName());
            RolePerms temp = new RolePerms();
            temp.setRid(role.getId());
            temp.setPid(perm.getId());
            rolePermsMapper.add(temp);
        }
        return 1;
    }
}
